<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Exampaper;
use app\common\model\ExamUserGrade;
use think\Db;
use think\exception\HttpResponseException;
use think\Request;

/**考试模块 */
class Exam extends Api
{

    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];


    /**
     * 考试分类
     * @return void 
     */
    public function examcate()
    {
        $list = Db::name('exam_cate')->where('status', '1')->field('id,name')->select();
        $this->success("OK", $list);
    }


    /**
     * 考试管理
     * @return void 
     */
    public function examPaperList()
    {
        $exam_cate_id = $this->request->param('exam_cate_id');
        $page = $this->request->param('page', 1);
        if (!$exam_cate_id) {
            $this->error("考试分类不能为空");
        }
        $list = (new Exampaper())->examPaperList(['exam_cate_id' => $exam_cate_id], $this->auth->id);
        $this->success("OK", $list);
    }


    /**考试页面 */
    public function examIndex()
    {
        $exam_paper_id = $this->request->param('exam_paper_id');
        $list = (new Exampaper())->getExamIndex($exam_paper_id, $this->auth->id);
        $this->success("OK", $list);
    }


    /**
     * 考试报名
     */
    public function examUserSignup()
    {
        $user = $this->auth->getUser();
        $info = Db::name('exam_user_signup')->where('user_id', $user->id)->find();
        if (empty($info)) {
            # 添加报名信息
            $rwo = Db::name('exam_user_signup')->insert([
                'user_id' => $user->id,
                'real_name' => $user->nickname,
                'phone' => $user->mobile,
                'status' => 0,
                'createtime' => time(),
            ]);
        } else {
            $rwo = Db::name('exam_user_signup')->where('id', $info['id'])->update([
                'real_name' => $user->nickname,
                'phone' => $user->mobile,
                'status' => 0,
                'message' => '',
                'updatetime' => time(),
            ]);
        }
        if ($rwo) {
            $this->success("报名成功，等待平台审核");
        } else {
            $this->error("报名失败");
        }
    }


    /**
     * 查询试卷
     * @return void 
     */
    public function examQuestion()
    {
        $exam_paper_id = $this->request->param('exam_paper_id'); # 试卷ID


        # 预创建考场考试记录
        $examGradeInfo = (new ExamUserGrade())->preExamGrade($exam_paper_id, $this->auth->id);
        # 获取考试信息和题库信息
        $question_data = (new Exampaper())->getExamQuestion($exam_paper_id, $this->auth->id);

        $this->success('ok', array_merge($question_data,  ['exam_grade_info' => $examGradeInfo]));
    }

    /**
     * 提交试卷
     */
    public function submit()
    {
        $request       = Request::instance();
        $user_id       = $this->auth->id;
        $exam_paper_id      = $request->post('exam_paper_id/d', 0); # 试卷ID
        $exam_grade_id = $request->post('exam_grade_id/d', 0); # 考场成绩ID
        $questions     = $request->post('questions/a', []); # 题目
        if (!$user_id || !$exam_paper_id || !$questions) {
            $this->error('提交数据有误' . $user_id);
        }
        $start_time = time();
        $result = (new Exampaper())->paperExamSubmit($user_id, $exam_paper_id, $questions, $start_time, $paper);
        $data = array_merge($result, [
            'paper_id' => $exam_paper_id,
            'is_pre' => 0, // 0结束考试
            'createtime' => time(), # 提交试卷时间
            'updatetime' => time(),
        ]);
        $row = (new ExamUserGrade())->where('id', $exam_grade_id)->update($data);
        $this->success('提交成功', $row);
    }



    /**中途退出考试 */
    public function updateUserGradeTime(Request $request)
    {
        $exam_grade_id = $request->param('exam_grade_id'); //成绩表id
        $grade_time = $request->param('grade_time'); //考试用时
        $grade = (new ExamUserGrade())->where('id',$exam_grade_id)->find();
        if ($grade) {
            $grade->grade_time = $grade_time; //考试用时
            $grade->updatetime = time();
            $grade->save(); //保存
        }
        $this->success('更新成功');
    }



    /**
     * 考试结果（考试成绩）
     * @return void 
     */
    public function getExamGradeInfo()
    {
        $exam_paper_id = $this->request->param('exam_paper_id', 0); # 试卷ID
        if ($exam_paper_id == 0) {
            $this->error('缺少参数');
        }
      
        $list = (new ExamUserGrade())->getExamGradeInfo($exam_paper_id, $this->auth->id);
        $this->success("OK", $list);
    }

    /**
     * 考试圆环图统计
     * @return void
     */
    public function donutChartStatistics(){
        $exam_paper_id = $this->request->param('exam_paper_id', 0); # 试卷ID
        if ($exam_paper_id == 0) {
            $this->error('缺少参数');
        }
        # 成绩表错题
        $error_ids = Db::name('exam_user_grade')->where([
            'paper_id' => $exam_paper_id,
            'user_id' => $this->auth->id,
        ])->value('error_ids');
        
        if (empty($error_ids)) {
            $this->success('圆环图统计数据', []);
        }
        
        # 将错题ID字符串转换为数组
        $error_ids_array = explode(',', $error_ids);
        
        # 根据错题ID查询题库表，并按模块统计错题数量
        $errorStats = Db::name('question')
            ->alias('q')
            ->join('mock m', 'q.mock_id = m.id')
            ->whereIn('q.id', $error_ids_array)
            ->field('q.mock_id, m.name as mock_name, COUNT(*) as error_count')
            ->group('q.mock_id')
            ->select();
        # 格式化返回数据
        $result = [];
        foreach ($errorStats as $item) {
            $result[] = [
                'name' => $item['mock_name'] ?: '未知模块',
                'value' => (int)$item['error_count']
            ];
        }
        $this->success('圆环图统计数据', $result);
    }

    /**
     * 查询题目解析
     * @return void 
     * @throws HttpResponseException 
     */
    public function getExamGradeQuestion()
    {
        $exam_grade_id = $this->request->param('exam_grade_id', 0);
        if ($exam_grade_id == 0) {
            $this->error('缺少参数');
        }
        $row = (new ExamUserGrade())->getExamGradeQuestion($exam_grade_id);
        $this->success('ok', $row);
    }

    /**
     * 查看考试排行
     * @return void 
     * @throws HttpResponseException 
     */
    public function getRankList()
    {
        $exam_paper_id = $this->request->param('exam_paper_id', 0); # 试卷ID
        if ($exam_paper_id == 0) {
            $this->error('缺少参数');
        }
        $row = (new ExamUserGrade())->getRankList($exam_paper_id, $this->auth->id);
        $this->success('ok', $row);
    }



}
